package com.dolawing.phonecallapp.phoneLog;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;


import com.dolawing.phonecallapp.phoneLog.CallDetails;

import java.util.Date;

@SuppressLint("Range")
public class PhoneCallUtils {
    private static String TAG = "CallLog";
    private static final String[] CALLLOGS_PROJECTION = new String[]{
            CallLog.Calls._ID,
            CallLog.Calls.CACHED_NAME,
            CallLog.Calls.NUMBER,
            CallLog.Calls.TYPE,
            CallLog.Calls.DATE,
            CallLog.Calls.DURATION
    };

    /**
     * 其实是查看一条数据
     * @param context
     * @return
     */
    public static CallDetails getLastOneCallDetails(Context context){
        CallDetails call = new CallDetails();
//        Uri contacts = CallLog.Calls.CONTENT_URI;

        Uri limitedCallLogUri;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
                    .appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, String.valueOf(1)).appendQueryParameter(ContentResolver.QUERY_ARG_OFFSET, String.valueOf(1)).appendQueryParameter("limit", String.valueOf(1)).build();
        }else {
            limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
                    .appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, String.valueOf(1)).appendQueryParameter("limit", String.valueOf(1)).build();
        }
        //projection表示columns 数据库列选择 不选则获取所有列
        Cursor managerCursor = context.getContentResolver().query(limitedCallLogUri, null, null, null, CallLog.Calls.DEFAULT_SORT_ORDER); // 按照时间逆序排列，最近打的最先显示

        int number = managerCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int duration = managerCursor.getColumnIndex(CallLog.Calls.DURATION);
        int date = managerCursor.getColumnIndex(CallLog.Calls.DATE);
        int type = managerCursor.getColumnIndex(CallLog.Calls.TYPE);
        Log.i("电话记录总数", "cursor count:" + managerCursor.getCount());
        int i = 0;
        while (managerCursor.moveToNext() && i < 1) {
            i++;
            String phNumber = managerCursor.getString(number);
            String callerName = getContactNameFromPhoneBook(context, phNumber);
            String callType = getTypeStr(managerCursor.getInt(managerCursor.getColumnIndex(CallLog.Calls.TYPE)));
//                String callType = getTypeStr(type);
            String callDate = managerCursor.getString(date);
            String callDayTime = new Date(Long.valueOf(callDate)).toString();
            String callDuration = managerCursor.getString(duration);

            call.setCallerName(callerName);
            call.setCallerNumber(phNumber);
            call.setCallDuration(callDuration);
            call.setCallType(callType);
            call.setCallTimeStamp(callDayTime);
        }
        managerCursor.close();
        System.out.println(call.toString());
        return call;
    }



    /**
     * 根据一个已知的电话号码，从通讯录中获取相对应的联系人姓名
     * @param context
     * @param phoneNum
     * @return
     */
    private static String getContactNameFromPhoneBook(Context context, String phoneNum) {
        String contactName = "";
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?",
                new String[] { phoneNum }, null);
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            cursor.close();
        }
        return contactName;
    }

    /**
     * 电话类型
     * @param type
     * @return
     */
    private static String getTypeStr(int type) {
        if (CallLog.Calls.INCOMING_TYPE == type) {
            return "来电";
        } else if (CallLog.Calls.OUTGOING_TYPE == type) {
            return "去电";
        }else if (CallLog.Calls.MISSED_TYPE == type) {
            return "未接";
        }else if (CallLog.Calls.VOICEMAIL_TYPE == type) {
            return "语音邮件";
        }else if (CallLog.Calls.REJECTED_TYPE == type) {
            return "拒绝";
        }else if (CallLog.Calls.BLOCKED_TYPE == type) {
            return "阻止";
        } else {
            return "未知";
        }
    }

    /**
     * 时间转换
     * @param duration
     * @return
     */
    private static String formatDuration(long duration) {
        StringBuilder sb = new StringBuilder();

        if (duration == 0) {
            sb.append("00:00");
        } else if (duration > 0 && duration < 60) {
            sb.append("00:");
            if (duration < 10) {
                sb.append("0");
            }
            sb.append(duration);

        } else if (duration > 60 && duration < 3600) {

            long min = duration / 60;
            long sec = duration % 60;
            if (min < 10) {
                sb.append("0");
            }
            sb.append(min);
            sb.append(":");

            if (sec < 10) {
                sb.append("0");
            }
            sb.append(sec);
        } else if (duration > 3600) {
            long hour = duration / 3600;
            long min = duration % 3600 / 60;
            long sec = duration % 3600 % 60;
            if (hour < 10) {
                sb.append("0");
            }
            sb.append(hour);
            sb.append(":");

            if (min < 10) {
                sb.append("0");
            }
            sb.append(min);
            sb.append(":");

            if (sec < 10) {
                sb.append("0");
            }
            sb.append(sec);
        }

        return sb.toString();
    }
}
